package com.example.batch_demo.config;

import jakarta.persistence.EntityManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.Objects;

/**
 * @Description jpa source config
 * @Author lihw
 * @Date 2023/12/14 14:53
 */
@Slf4j
@Configuration
@EnableJpaRepositories(basePackages = {"com.example.batch_demo.repository.target"},
        entityManagerFactoryRef = "targetLocalContainerEntityManagerFactoryBean",
        transactionManagerRef = "targetPlatformTransactionManager")
public class JpaConfigTarget {

    @Autowired
    @Qualifier("dataSource")
    private DataSource targetDataSource;

    @Autowired
    JpaProperties jpaProperties;

    @Primary
    @Bean(name = "targetEntityManager")
    public EntityManager targetEntityManager(EntityManagerFactoryBuilder builder) {
        return targetLocalContainerEntityManagerFactoryBean(builder).getObject().createEntityManager();
    }
    @Primary
    @Bean
    public LocalContainerEntityManagerFactoryBean targetLocalContainerEntityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(targetDataSource)
                .packages("com.example.batch_demo.entity.target")
                .properties(jpaProperties.getProperties())
                .persistenceUnit("target")
                .build();
    }
    @Primary
    @Bean
    public PlatformTransactionManager targetPlatformTransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(Objects.requireNonNull(targetLocalContainerEntityManagerFactoryBean(builder).getObject()));
    }
}
